document.addEventListener('DOMContentLoaded', function () {
    const recordsPerPageSelect = document.getElementById('recordsPerPage');
    let currentPage = 1;
    let recordsPerPage = parseInt(recordsPerPageSelect.value);

    // 请求后端，获取并渲染数据
    function fetchAndRenderData(page, size) {
        const ip = document.getElementById('ipInput').value;
        const personInCharge = document.getElementById('personInChargeInput').value;
        const systemName = document.getElementById('systemNameInput').value;
        const serverUser = document.getElementById('serverUserInput').value;
        const command = document.getElementById('commandInput').value;

        const url = `/xxl-job-admin/cronjobs/search?ip=${ip}&owner=${personInCharge}&systemName=${systemName}&serverUser=${serverUser}&command=${command}&page=${page}&size=${size}`;
        fetch(url)
            .then(response => response.json())
            .then(data => {
                renderTable(data.data);           // 渲染表格
                renderPagination(data.page, data.total, data.size);  // 渲染分页
            })
            .catch(error => {
                console.error('查询失败:', error);
            });
    }

    // 渲染表格数据
    function renderTable(jobs) {
        const tableBody = document.getElementById('cronjob_list').getElementsByTagName('tbody')[0];
        tableBody.innerHTML = '';  // 清空表格内容

        // 遍历任务列表并渲染表格行
        jobs.forEach(job => {
            const row = document.createElement('tr');
            const encodedCommand = encodeURIComponent(job.command); // 编码 command
            row.innerHTML = `
            <td>
                <input type="checkbox" class="select-cronjob" data-id="${job.id}" style="margin-right: 10px;">
            </td>
            <td>${job.ip}</td>
            <td>${job.owner}</td>
            <td>${job.systemName}</td>
            <td>${job.schedule}</td>
            <td>${job.command}</td>
            <td>${job.serverUser}</td>
            <td>${job.status === 1 ? '生效' : '不生效'}</td>
            <td>${job.updatedAt || ''}</td>
            <td>
                <button class="btn btn-info btn-edit" data-id="${job.id}">编辑</button>
                <button class="btn btn-warning btn-disable" 
                        data-id="${job.id}" 
                        data-schedule="${job.schedule}" 
                        data-command="${encodedCommand}" 
                        data-serverip="${job.ip}"
                        data-serverUser="${job.serverUser}">注释</button>
                <button class="btn btn-success btn-enable" 
                        data-id="${job.id}" 
                        data-schedule="${job.schedule}" 
                        data-command="${encodedCommand}" 
                        data-serverip="${job.ip}"
                        data-serverUser="${job.serverUser}">启用</button>
            </td>
        `;
            tableBody.appendChild(row);
        });

        // 确保在渲染表格后重新绑定全选功能
        bindSelectAllFeature();

        // 为每个 "注释" 按钮添加点击事件
        document.querySelectorAll('.btn-disable').forEach(button => {
            button.addEventListener('click', function () {
                const jobId = this.getAttribute('data-id');          // 获取任务ID
                const schedule = this.getAttribute('data-schedule');  // 获取调度时间
                const command = decodeURIComponent(this.getAttribute('data-command'));    // 获取任务命令
                const serverIp = this.getAttribute('data-serverip');  // 获取服务器IP
                const serverUser = this.getAttribute('data-serverUser');  // 获取服务器user

                // 调用封装的二次认证逻辑
                showSecondaryAuthModal((verifyUser, ticketNumber) => {
                    disableCronJob(jobId, schedule, command, serverIp,serverUser,verifyUser, ticketNumber);   // 调用禁用任务函数
                });
            });
        });

        // 批量禁用任务
        document.getElementById('bulkDisableBtn').addEventListener('click', function () {
            const selectedJobs = Array.from(document.querySelectorAll('.select-cronjob:checked')); // 获取所有选中的任务
            if (selectedJobs.length === 0) {
                alert('请先选择要注释的任务！');
                return;
            }

            // 收集任务的必要信息
            const jobDetails = selectedJobs.map(checkbox => {
                const row = checkbox.closest('tr');
                return {
                    jobId: checkbox.getAttribute('data-id'),
                    schedule: row.querySelector('[data-schedule]').getAttribute('data-schedule'),
                    command: decodeURIComponent(row.querySelector('[data-command]').getAttribute('data-command')),
                    serverIp: row.querySelector('[data-serverip]').getAttribute('data-serverip'),
                    serverUser: row.querySelector('[data-serverUser]').getAttribute('data-serveruser')
                };
            });

            // 调用二次认证
            showSecondaryAuthModal((verifyUser, ticketNumber) => {
                processJobsInBatch(jobDetails, verifyUser, ticketNumber);
            });
        });

        // 启用任务的逻辑
        document.querySelectorAll('.btn-enable').forEach(button => {
            button.addEventListener('click', function () {
                const jobId = this.getAttribute('data-id');
                const schedule = this.getAttribute('data-schedule');
                const command = decodeURIComponent(this.getAttribute('data-command'));
                const serverIp = this.getAttribute('data-serverip');
                const serverUser = this.getAttribute('data-serverUser');  // 获取服务器user

                // 在调用 enableCronJob 前打印日志
                console.log("启用任务数据：", {
                    jobId: jobId,
                    schedule: schedule,
                    command: command,
                    serverIp: serverIp,
                    serverUser: serverUser
                });

                // 调用封装的二次认证逻辑
                showSecondaryAuthModal((verifyUser, ticketNumber) => {
                    enableCronJob(jobId, schedule, command, serverIp,serverUser, verifyUser, ticketNumber);
                });
            });
        });

        // 批量启用任务
        document.getElementById('bulkEnableBtn').addEventListener('click', function () {
            const selectedJobs = Array.from(document.querySelectorAll('.select-cronjob:checked')); // 获取所有选中的任务
            if (selectedJobs.length === 0) {
                alert('请先选择要启用的任务！');
                return;
            }

            // 收集任务的必要信息
            const jobDetails = selectedJobs.map(checkbox => {
                const row = checkbox.closest('tr');
                return {
                    jobId: checkbox.getAttribute('data-id'),
                    schedule: row.querySelector('[data-schedule]').getAttribute('data-schedule'),
                    command: decodeURIComponent(row.querySelector('[data-command]').getAttribute('data-command')),
                    serverIp: row.querySelector('[data-serverip]').getAttribute('data-serverip'),
                    serverUser: row.querySelector('[data-serverUser]').getAttribute('data-serveruser')
                };
            });

            // 调用二次认证
            showSecondaryAuthModal((verifyUser, ticketNumber) => {
                processJobsInBatchEnable(jobDetails, verifyUser, ticketNumber);
            });
        });

        // 编辑任务的逻辑
        document.querySelectorAll('.btn-edit').forEach(button => {
            button.addEventListener('click', function () {
                const jobId = this.getAttribute('data-id');

                // 调用后端接口获取任务详情
                fetch(`http://localhost:8089/xxl-job-admin/cronjobs/detail/${jobId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 填充弹窗表单
                            document.getElementById('editJobId').value = jobId;
                            document.getElementById('editOwner').value = data.owner;
                            document.getElementById('editSystemName').value = data.systemName;
                            document.getElementById('editSchedule').value = data.schedule;
                            document.getElementById('editCommand').value = data.command;
                            document.getElementById('editIp').value = data.ip;
                            document.getElementById('editServerUser').value = data.serverUser;
                            document.getElementById('editStatus').value = data.status === 1 ? '生效' : '不生效';
                            document.getElementById('editUptime').value = data.uptime;

                            // 显示编辑弹窗
                            $('#editModal').modal('show');

                            // 绑定保存按钮的点击事件，进行二次认证
                            const saveEditBtn = document.getElementById('saveBtn');

                            // 移除之前的事件监听器
                            const newSaveEditBtn = saveEditBtn.cloneNode(true);
                            saveEditBtn.parentNode.replaceChild(newSaveEditBtn, saveEditBtn);

                            newSaveEditBtn.addEventListener('click', function (event) {
                                event.preventDefault();
                                event.stopPropagation();

                                // 关闭编辑模态框
                                $('#editModal').modal('hide');

                                // 显示二次认证模态框
                                showSecondaryAuthModal((verifyUser, ticketNumber) => {
                                    // 二次认证通过后，执行保存操作
                                    saveTask(verifyUser, ticketNumber);
                                });
                            });
                        } else {
                            alert('查询任务失败');
                        }
                    })
                    .catch(error => {
                        console.error("获取任务详情失败:", error);
                    });
            });
        });

        // 新增任务的逻辑
        document.getElementById('addTaskBtn').addEventListener('click', function () {
            // 打开新增任务的模态框
            $('#addModal').modal('show');

            // 设置调度时间输入框的状态检测
            const addScheduleInput = document.getElementById('addSchedule');
            const statusField = document.getElementById('addStatus');

            // 设置输入框的监听器，当调度时间以#开头时，状态自动变为不生效
            addScheduleInput.addEventListener('input', function () {
                if (addScheduleInput.value.startsWith('#')) {
                    statusField.value = '不生效';
                } else {
                    statusField.value = '生效';
                }
            });

            // 绑定保存新增任务按钮的点击事件，进行二次认证
            const saveNewTaskBtn = document.getElementById('saveNewTaskBtn');
            const newSaveNewTaskBtn = saveNewTaskBtn.cloneNode(true);
            saveNewTaskBtn.parentNode.replaceChild(newSaveNewTaskBtn, saveNewTaskBtn);
            newSaveNewTaskBtn.addEventListener('click', function () {
                $('#addModal').modal('hide');  // 关闭新增模态框
                showSecondaryAuthModal((verifyUser, ticketNumber) => {
                    saveNewTask(verifyUser, ticketNumber);  // 认证通过后，执行保存操作
                });
            });
        });

        // 绑定定时任务初始化按钮事件
        document.getElementById('initTaskBtn').addEventListener('click', function () {
            // 禁用按钮，防止重复点击
            const initTaskBtn = document.getElementById('initTaskBtn');
            initTaskBtn.disabled = true;

            // 显示二次认证模态框
            showSecondaryAuthModal((verifyUser, ticketNumber) => {
                // 二次认证通过后，执行初始化请求
                fetch('http://localhost:8089/xxl-job-admin/cronjobs/init', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        verifyUser: verifyUser,
                        ticketNumber: ticketNumber
                    })
                }).then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('定时任务初始化成功');
                            fetchAndRenderData(currentPage, recordsPerPage);
                        } else {
                            alert('定时任务初始化失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('定时任务初始化失败:', error);
                    })
                    .finally(() => {
                        // 请求完成后，恢复按钮状态
                        initTaskBtn.disabled = false;
                    });
            });
        });
    }
    // 绑定全选功能的函数
    function bindSelectAllFeature() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const tableBody = document.getElementById('cronjob_list').getElementsByTagName('tbody')[0];

        if (!selectAllCheckbox || !tableBody) {
            console.error("全选复选框或表格内容未找到！");
            return;
        }

        // 绑定全选复选框的事件
        selectAllCheckbox.addEventListener('change', function () {
            const isChecked = selectAllCheckbox.checked;
            const checkboxes = tableBody.querySelectorAll('.select-cronjob');
            checkboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
        });

        // 监听单个复选框状态，更新全选框状态
        tableBody.addEventListener('change', function (event) {
            if (event.target.classList.contains('select-cronjob')) {
                const checkboxes = tableBody.querySelectorAll('.select-cronjob');
                const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
                const someChecked = Array.from(checkboxes).some(checkbox => checkbox.checked);

                selectAllCheckbox.checked = allChecked;
                selectAllCheckbox.indeterminate = !allChecked && someChecked;
            }
        });
    }

    // 禁用定时任务的函数
    function disableCronJob(jobId, schedule, command, serverIp, serverUser, verifyUser, ticketNumber, isBatch = false) {
        const data = {
            jobId: jobId,
            schedule: schedule,
            command: command,
            serverIp: serverIp,
            serverUser: serverUser,
            verifyUser: verifyUser,
            ticketNumber: ticketNumber
        };

        return fetch('http://localhost:8089/xxl-job-admin/cronjobs/disable', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(result => {
                if (!result.success) {
                    throw new Error(result.message || "未知错误");
                }

                // 如果不是批量调用，返回提示并刷新页面
                if (!isBatch) {
                    alert("任务禁用成功！");
                    fetchAndRenderData(currentPage, recordsPerPage);
                }

                return result; // 返回结果供批量调用使用
            })
            .catch(error => {
                if (!isBatch) {
                    alert("任务禁用失败：" + error.message);
                }
                throw new Error(`禁用任务失败：${error.message}`);
            });
    }


    // 批量禁用任务的处理函数
    async function processJobsInBatch(jobs, verifyUser, ticketNumber) {
        try {
            for (const job of jobs) {
                // 每个任务调用禁用函数
                await disableCronJob(
                    job.jobId,
                    job.schedule,
                    job.command,
                    job.serverIp,
                    job.serverUser,
                    verifyUser,
                    ticketNumber,
                    true
                );
            }
            alert('所有任务已成功禁用！');
            fetchAndRenderData(currentPage, recordsPerPage); // 统一刷新表格
        } catch (error) {
            // 如果发生错误，终止操作并提示用户
            alert(`任务禁用失败！\n任务IP: ${job.serverIp}\n指令: ${job.command}\n错误: ${error.message}`);
        }
    }


    // 启用定时任务的函数
    function enableCronJob(jobId, schedule, command, serverIp, serverUser, verifyUser, ticketNumber, isBatch = false) {
        const data = {
            jobId: jobId,
            schedule: schedule,
            command: command,
            serverIp: serverIp,
            serverUser: serverUser,
            verifyUser: verifyUser,
            ticketNumber: ticketNumber
        };

        console.log("发送的数据：", JSON.stringify(data));

        return fetch('http://localhost:8089/xxl-job-admin/cronjobs/enable', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(result => {
                if (!result.success) {
                    throw new Error(result.message || "未知错误");
                }

                // 如果不是批量调用，返回提示并刷新页面
                if (!isBatch) {
                    alert("任务启用成功！");
                    fetchAndRenderData(currentPage, recordsPerPage);
                }

                return result; // 返回结果供批量调用使用
            })
            .catch(error => {
                if (!isBatch) {
                    alert("任务启用失败：" + error.message);
                }
                throw new Error(`启用任务失败：${error.message}`);
            });
    }

    // 批量启用任务的处理函数
    async function processJobsInBatchEnable(jobs, verifyUser, ticketNumber) {
        try {
            for (const job of jobs) {
                // 每个任务调用启用函数，设置 isBatch 为 true
                await enableCronJob(
                    job.jobId,
                    job.schedule,
                    job.command,
                    job.serverIp,
                    job.serverUser,
                    verifyUser,
                    ticketNumber,
                    true // 表示批量调用
                );
            }
            alert('所有任务已成功启用！');
            fetchAndRenderData(currentPage, recordsPerPage); // 统一刷新表格
        } catch (error) {
            // 如果发生错误，终止操作并提示用户
            alert(`任务启用失败！\n任务IP: ${job.serverIp}\n指令: ${job.command}\n错误: ${error.message}`);
        }
    }


    // 保存任务函数
    function saveTask(verifyUser, ticketNumber) {
        const jobId = document.getElementById('editJobId').value;
        const schedule = document.getElementById('editSchedule').value;
        const command = document.getElementById('editCommand').value;
        const owner = document.getElementById('editOwner').value;
        const systemName = document.getElementById('editSystemName').value;
        const serverIp = document.getElementById('editIp').value;
        const serverUser = document.getElementById('editServerUser').value;

        const data = { jobId, schedule, command, owner, systemName, serverIp,serverUser,verifyUser, ticketNumber };

        fetch('http://localhost:8089/xxl-job-admin/cronjobs/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        }).then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('任务保存成功');
                    fetchAndRenderData(currentPage, recordsPerPage);
                } else {
                    alert('任务保存失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('任务保存失败:', error);
            });
    }

    // 保存新增任务函数
    function saveNewTask(verifyUser, ticketNumber) {
        const ip = document.getElementById('addIp').value;
        const owner = document.getElementById('addOwner').value;
        const systemName = document.getElementById('addSystemName').value;
        const serverUser = document.getElementById('addServerUser').value;
        const schedule = document.getElementById('addSchedule').value;
        const command = document.getElementById('addCommand').value;
        const status = schedule.startsWith('#') ? 0 : 1;  // 如果调度时间前面有#，状态为不生效

        const data = { ip, owner, systemName, schedule, command, status,serverUser, verifyUser, ticketNumber };

        fetch('http://localhost:8089/xxl-job-admin/cronjobs/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        }).then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('任务新增成功');
                    fetchAndRenderData(currentPage, recordsPerPage);  // 刷新页面
                } else {
                    alert('任务新增失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('任务新增失败:', error);
            });
    }

    // 封装二次认证逻辑
    function showSecondaryAuthModal(onSuccess) {
        // 显示模态框
        $('#saveModal').modal({});

        const saveTaskBtn = document.getElementById('saveTaskBtn');

        // 移除之前的事件监听器
        const newSaveTaskBtn = saveTaskBtn.cloneNode(true);
        saveTaskBtn.parentNode.replaceChild(newSaveTaskBtn, saveTaskBtn);

        // 绑定新的点击事件监听器
        newSaveTaskBtn.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();

            const verifyUser = document.getElementById('verifyUserSecondary').value;
            const verifyPassword = document.getElementById('verifyPasswordSecondary').value;
            const ticketNumber = document.getElementById('ticketNumber').value;

            // 校验工单号是否填写
            if (!ticketNumber) {
                alert('请填写工单号');
                return;
            }

            // 验证用户身份
            fetch('http://localhost:8089/xxl-job-admin/verified/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: verifyUser,
                    password: verifyPassword
                })
            }).then(response => response.json())
                .then(result => {
                    if (result.success) {
                        onSuccess(verifyUser, ticketNumber);  // 认证成功后执行回调
                        $('#saveModal').modal('hide');  // 关闭模态框
                    } else {
                        alert(result.message || '身份验证失败，请稍后重试');
                    }
                })
                .catch(error => {
                    console.error('身份验证失败:', error);
                    alert('请求发送失败，请检查网络连接或稍后再试');
                });
        });
    }

    // 渲染分页控件
    function renderPagination(currentPage, totalItems, pageSize) {
        // 分页代码保持不变
    }

    function renderPagination(currentPage, totalItems, pageSize) {
        const totalPages = Math.ceil(totalItems / pageSize);
        const paginationElement = document.getElementById('pagination');
        paginationElement.innerHTML = '';  // 清空之前的分页内容

        // 第一行：显示当前页码和总页数
        const pageIndicator = document.createElement('div');
        pageIndicator.style.marginBottom = '10px';  // 增加行间距
        pageIndicator.innerText = `第 ${currentPage} 页，共 ${totalPages} 页`;
        paginationElement.appendChild(pageIndicator);

        // 第二行：显示当前页条数和总记录数
        const pageInfo = document.createElement('div');
        const currentRecordCount = Math.min(pageSize, totalItems - (currentPage - 1) * pageSize);
        pageInfo.innerText = `当前记录条数 ${currentRecordCount} / ${pageSize} ，共 ${totalItems} 条`;
        paginationElement.appendChild(pageInfo);

        // 创建分页按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.style.marginTop = '10px';  // 增加按钮和文本的间距

        // 创建上一页按钮
        if (currentPage > 1) {
            const prevPage = document.createElement('button');
            prevPage.innerText = '上一页';
            prevPage.style.marginRight = '5px';  // 增加按钮间距
            prevPage.addEventListener('click', () => fetchAndRenderData(currentPage - 1, pageSize));
            buttonContainer.appendChild(prevPage);
        }

        // 创建下一页按钮
        if (currentPage < totalPages) {
            const nextPage = document.createElement('button');
            nextPage.innerText = '下一页';
            nextPage.style.marginLeft = '5px';  // 增加按钮间距
            nextPage.addEventListener('click', () => fetchAndRenderData(currentPage + 1, pageSize));
            buttonContainer.appendChild(nextPage);
        }

        paginationElement.appendChild(buttonContainer);  // 将按钮容器添加到分页元素中
    }

    // 初始化，加载第一页的数据
    fetchAndRenderData(currentPage, recordsPerPage);

    // 绑定搜索按钮事件
    document.getElementById('searchBtn').addEventListener('click', function () {
        currentPage = 1;
        fetchAndRenderData(currentPage, recordsPerPage);
    });

    // 绑定每页显示条数更改事件
    recordsPerPageSelect.addEventListener('change', function () {
        recordsPerPage = parseInt(this.value);
        currentPage = 1;
        fetchAndRenderData(currentPage, recordsPerPage);
    });

});
